﻿using AntdUI;
using FastReport.RichTextParser;
using Modbus;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PrintLabel.Model;
using PrintLabel.Tools;
using PrintLabel.View;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Media3D;
using Tools;
using 纺织贸易管理系统;

namespace PrintLabel
{
    public partial class Main : Form
    {
        private Modbus.ComService comService = new Modbus.ComService();
        private List<ChiDianTable> Defects = new List<ChiDianTable>();
        private StockTable Stock;
        private InspectionNoticeNeedDetail Detail;
        private int OldRollID = 0;
        private JuanHaoTable QueryRoll = new JuanHaoTable();
        private Parameter param = new Parameter() { BaudRate = "9600", Database = "Textiletradedb", Server = "192.168.0.109,1433", Stopwatch = "德莱宝", ComNum = "Com1" };
        public Main()
        {
            InitializeComponent();
            label28.Text = string.Empty;
        }

        private void LoadRolls()
        {
            table1.DataSource = dbContext.dbcontext.Queryable<JuanHaoTable>().Where(x => x.MachineID == txtjitaihao.Text && x.rq >= DateTime.Today).OrderByDescending(x => x.ID).ToList();
            ReflashFinishNum();
        }
        private void Main_Load(object sender, EventArgs e)
        {

            table4.Columns = new AntdUI.ColumnCollection()
            {
                new AntdUI.Column ("NeedNum","需求数"),
                new AntdUI.Column ("FinishNum","完成数"), 
                new AntdUI.Column ("Kuanhao","款号"), 
                new AntdUI.Column ("Unit","单位"), 
                new AntdUI.Column ("color","颜色"),
                 new AntdUI.Column ("OrderNum","订单号"),
                  new AntdUI.Column ("ContractNum","合同号"),
                new AntdUI.Column ("sampleNum","编号"),
                new AntdUI.Column ("sampleName","品名"),
                 new AntdUI.Column ("CustomerPingMing","客户品名"),
                new AntdUI.Column ("CustomerColorNum","客户颜色"),

            };
            ///检查是否需要更新
            Task.Run(() =>
            {
                Boolean isupdate = new CheckUpdate.CheckUpdate() { LocalPath = Application.StartupPath }.IsNeedUpdate();
                if (isupdate)
                {
                    MessageBox.Show("有新的版本需要更新！系统将关闭。");
                    Process.Start(Application.StartupPath + "\\Updater.exe");
                    KillSelf.Kill();
                }
            });
            CreateTable(table1);
            CreateTable(table2);
            CreateDefectTable();
            
            cmbDanwei.Text = "米";
            comService.SetUnit(cmbDanwei.Text);
            var filepath = Application.StartupPath + "//Setting.json";

            if (File.Exists(filepath))
            {
                string json = File.ReadAllText(filepath);
                param = JsonConvert.DeserializeObject<Parameter>(json);
                dbContext.dbcontext = new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                {
                    ConnectionString = $"server={param.Server};uid=sa;pwd=Kc123456;database={param.Database}",
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = SqlSugar.InitKeyType.Attribute
                });
                cmbCopies.Text = param.Copies.ToString();
                txtjitaihao.Text = param.MachineID.ToString();
                chkzidongjuanhao.Checked = param.AutoRollNumber;
            }
            else
            {
                File.WriteAllText(filepath, JsonConvert.SerializeObject(param));
            }
            //加载跳电未保存的疵点信息
            var temp = FileHelper.读取信息();
            Defects = temp.Defects;
            table3.DataSource = Defects;
            Detail= temp.Detail;
            if (Detail!=null)
            {
                LoadInspectionNotice(Detail);
            }
            Stock = temp.Stock;
            if (Stock!=null)
            {
                LoadLot(Stock);
            } 
            //加载跳电未保存的通知单信息

            txtjitaihao.Text = param.MachineID.ToString();
            var requestCode = GetMachineCodeHelper.GenerateRequestCode(GetMachineCodeHelper.GetMachineCode());
            if (!GetMachineCodeHelper.ValidateRegisterCode(param.RegisterCode))
            {
                ShowMessage.ShowErrorMessagebox(this, "注册码失败！注册码不准确");
                new 注册(requestCode).ShowDialog();
            }
            param.RegisterCode = GetMachineCodeHelper.GenerateRegisterCode(requestCode);
            try
            {
                cmbLabels.Items.AddRange(Tools.ShippingmarkHelper.获取所有模板().ToArray());
                cmbOutShippingmark.Items.AddRange(Tools.ShippingmarkHelper.获取所有模板().ToArray());
                cmbLabels.Text = param.Shippingmark;
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "获取唛头模板的时候发生了错误：" + ex.Message);
            }

            try
            {
                comService.Stopwatch = param.Stopwatch;
                comService.BaudRate = param.BaudRate.ObjToInt();
                comService.打开端口(param.ComNum);
                timer1.Start();
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "打开串口的时候发生了错误：" + ex.Message);
            }
            ShippingmarkHelper.DownLoadShinppingmark(Application.StartupPath);
            ShippingmarkHelper.DownLoadCheckReport(Application.StartupPath);
            LoadRolls();
            CreateCidianBtn();
        }
        private void CreateDefectTable()
        {
            table3.AutoSizeColumnsMode = AntdUI.ColumnsMode.Fill;
            table3.Columns = new AntdUI.ColumnCollection()
            {
                 new AntdUI.Column ("ChiDianName","疵点名称"),
                new AntdUI.Column ("WeiZhi","位置"),
                 new AntdUI.Column ("ShuLiang","长度"),
                 new AntdUI.Column ("KouFeng","扣分"),
                  new AntdUI.Column ("IsALL","通匹"),
                   new AntdUI.Column ("EdgeDistance","边距"),
            };
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                comService.发送数据();
                if (Regex.IsMatch(comService.数字, @"^[+-]?\d*[.]?\d*$"))
                {
                    cmbDanwei.Text = string.IsNullOrWhiteSpace(comService.GetUnite()) ? "米" : comService.GetUnite();
                    txtLength.Text = (double.Parse(comService.数字)).ToString("N2");
                }
            }
            catch (Exception ex)
            {
                timer1.Stop();
                switch1.Checked = false;
                ShowMessage.ShowErrorMessagebox(this, "读取码表的数字的时候发生了错误！" + ex.Message);

            }
        }
        private string CreateBarcode()
        {
            var danhao = "JH" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
            danhao += DateTime.Now.Second.ToString() + txtganghao.Text + txtjuanhao.Text;
            return danhao;
        }
        private JuanHaoTable CreateNewRoll()
        {
            OrderTable order = new OrderTable();
            if (!string.IsNullOrEmpty(txtOrdernum.Text))
            {
                order = dbContext.dbcontext.Queryable<OrderTable>().First(x => x.OrderNum == txtOrdernum.Text);
            }
            if (Stock == null)
            {
                Stock = new StockTable();
            }
            var roll = new JuanHaoTable()
            {

                yanse = txtyanse.Text,
                MaShu = txtguama.Value,
                GangHao = txtganghao.Text,
                SampleName = txtpingming.Text,
                biaoqianmishu = Math.Truncate(txtLength.Text.ObjToDecimal() / txtguama.Text.ObjToDecimal() * 100) - txtzengsong.Text.ObjToDecimal(),
                PiHao = txtjuanhao.Text.ObjToInt(),
                rq = DateTime.Now,
                JuanHao = CreateBarcode(),
                MachineID = txtjitaihao.Text,
                CheckID = txtjianyanyuan.Text,
                Danwei = cmbDanwei.Text,
                JiaJian = txtzengsong.Text.ObjToDecimal(),
                Ckmc = txtStockname.Text,
                CustomerPingMing = txtCustomFricename.Text,
                CustomerColorNum = txtCustomColor.Text,
                SampleNum = txtBianhao.Text,
                Hetonghao = txtHetonghao.Text,
                DengJI = txtDengji.Text,
                OrderNum = txtOrdernum.Text,
                state = 0,
                Kezhong = txtkezhong.Text,
                Menfu = txtmenfu.Text,
                kuanhao = txtKuanhao.Text,
                MiShu = txtLength.Text.ObjToDecimal(),
                CustomerName = order == null ? string.Empty : order.CustomerName,
                Density = Detail == null ? Stock.Density : Detail.Density,
                EnglishName = Detail == null ? Stock.EnglishName : Detail.EnglishName,
                SecondaryEncoding = Detail == null ? Stock.SecondaryEncoding : Detail.SecondaryEncoding,
                Saleman = order == null ? string.Empty : order.SaleMan,
                Composition = Detail == null ? Stock.CF : Detail.Component,
                guige = Detail == null ? Stock.GG : Detail.Specifications,
                Huahao = Detail == null ? Stock.Huahao : Detail.Huahao,
                Weight = txtWeight.Text.ToDecimal(),
                Houzhengli = Stock.houzhengli,
                InspectionNoticeNum = Detail == null ? string.Empty : Detail.InspectionNoticeNum,
                SumKouFeng = Defects.Sum(x => x.KouFeng),
                Consignee = groupBox1.Text,
                CheckStyle = radio中检.Checked ? "中检" : radio库存.Checked ? "库存 " : "配货",
                Cidian=txtbeizhu.Text.Trim(),
                CustomerLotNo=Stock.ID.ToString(),
            };
            //foreach (var item in Defects)
            //{
            //    roll.Cidian += "{";
            //    roll.Cidian += "疵点名称" + item.ChiDianName.Split('(')[0] + ",";
            //    roll.Cidian += "位置" + item.WeiZhi + ",";
            //    roll.Cidian += "长度" + item.ShuLiang.ToString("N2") + ",";
            //    roll.Cidian += "扣分米" + item.KouFeng.ToString("N0") + ",";
            //    roll.Cidian += "疵点备注" + item.BeiZhu + "'";
            //    roll.Cidian += "}";
            //}
            //如果是复检
            if (checkbox1.Checked)
            {
                var oldroll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.ID == OldRollID);
                if (oldroll != null)
                {
                    roll.Density = oldroll.Density;
                    roll.EnglishName = oldroll.EnglishName;
                    roll.SecondaryEncoding = oldroll.SecondaryEncoding;
                    roll.Composition = oldroll.Composition;
                    roll.guige = oldroll.guige;
                    roll.Huahao = oldroll.Huahao;
                    roll.Houzhengli = oldroll.Houzhengli;
                    roll.InspectionNoticeNum = oldroll.InspectionNoticeNum;
                }
            }
            //if(!checkbox1.Checked)
            //{
            //    if(radio库存.Checked)
            //    {
            //        roll.kuanhao = "库存";
            //    }
            //    if(radio中检.Checked)
            //    {
            //        roll.kuanhao = "中检";
            //    }
            //}
            return roll;
        }
        /// <summary>
        /// 检查等级是否填写
        /// </summary>
        /// <returns></returns>
        private Boolean CheckDengji()
        {
            while (string.IsNullOrEmpty(txtDengji.Text))
            {
                txtDengji_Click(null, null);
            }
            return true;
        }
        /// <summary>
        /// 检查等级是否填写
        /// </summary>
        /// <returns></returns>
        private Boolean CheckLotNo()
        {
           if(string.IsNullOrEmpty(txtganghao.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "请选择一下缸号");
            }
            return true;
        }
        /// <summary>
        /// 检查时候超过需求数
        /// </summary>
        /// <returns></returns>
        private Boolean CheckNeed()
        {
            if (Detail != null)
            {
                if (radio配货.Checked)
                {
                    if (Detail.FinishNum >= Detail.NeedNum * (decimal)(1 -  ( Detail.Loss.Replace("%", "")) .ToDecimal() / 100))
                    {
                        var res = MessageBox.Show(this, "已检验数大于需求数的下限！是否继续","询问",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
                        if (res== DialogResult.Cancel)
                        {
                            return false;
                        }
                    }
                }
            }
            if (radio配货.Checked)
            {
                var detail=table4.DataSource as List<InspectionNoticeNeedDetail>;
                if (detail == null||detail.Count==0)
                {
                    ShowMessage.ShowErrorMessagebox(this, "请配货模式下请加载一下通知单！");
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 保存前的检查
        /// </summary>
        /// <returns></returns>
        private Boolean BeginSave()
        {
            if (string.IsNullOrEmpty(txtStockname.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "请选择一下仓库");
                return false;
            }
            if (txtLength.Text.ObjToDecimal() == 0)
            {
                ShowMessage.ShowErrorMessagebox(this, "长度不能为0");
                return false;
            }
            if (string.IsNullOrEmpty(txtganghao.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "缸号不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(txtyanse.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "颜色不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(txtBianhao.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "布料编号不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(txtpingming.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "布料品名不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(txtmenfu.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "门幅不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(txtjianyanyuan.Text))
            {
                ShowMessage.ShowErrorMessagebox(this, "检验员不能为空");
                return false;
            }
            return true;
        }
        private JuanHaoTable Save()
        {
            try
            {
                var roll = CreateNewRoll();
                //如果不是复检补全卷号
                if (!checkbox1.Checked)
                {
                    if (param.AutoRollNumber)
                    {
                        var pihao = RollHelper.CreatGangJuanhao(roll);
                        if (pihao != roll.PiHao)
                        {
                            ShowMessage.ShowErrorMessagebox(this, "当前缸号已经存在卷号为" + roll.PiHao.ToString() + "的卷，系统将自动补号成"+pihao.ToString());
                            roll.PiHao = pihao;
                        }
                    }
                }
                dbContext.dbcontext.BeginTran();
                //如果是复检的话先查找检验通知单 取消已完成数量 然后再加上新的数量
                if (checkbox1.Checked)
                {
                    var noticeneeddetail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.InspectionNoticeNum == roll.InspectionNoticeNum &&
                    x.sampleNum == roll.SampleNum && x.Kuanhao == roll.kuanhao && x.OrderNum == roll.OrderNum && x.color == roll.yanse);
                    if (noticeneeddetail != null)
                    {
                        var oldroll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.ID == OldRollID);
                        if (oldroll != null)
                        {
                            if (oldroll.DengJI == "A")
                            {
                                noticeneeddetail.FinishNum -= oldroll.biaoqianmishu;
                                dbContext.dbcontext.Updateable(noticeneeddetail).ExecuteCommand();
                            }
                        }
                        //复检的时候删除原先的疵点信息
                        oldroll.state = 1;
                        oldroll.Danhao = "复检";
                        oldroll.CheckStyle = "复检";
                    }

                }
                //保存疵点
                if (Defects.Count > 0)
                {
                    Defects.ForEach(item => { item.JuanHao = roll.JuanHao; });
                    dbContext.dbcontext.Insertable(Defects).ExecuteCommand();
                }
                if (roll.DengJI == "A")
                {

                    if (!checkbox1.Checked)
                    {
                        ///不是复检的话直接加上新的数量
                        if (Detail != null)
                        {
                            Detail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.ID == Detail.ID);
                            Detail.FinishNum += roll.biaoqianmishu;
                            dbContext.dbcontext.Updateable(Detail).ExecuteCommand();
                        }
                    }
                    else
                    {
                        var noticeneeddetail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.InspectionNoticeNum == roll.InspectionNoticeNum &&
                                                            x.sampleNum == roll.SampleNum && x.Kuanhao == roll.kuanhao && x.OrderNum == roll.OrderNum && x.color == roll.yanse);
                        if (noticeneeddetail != null)
                        {
                            noticeneeddetail.FinishNum += roll.biaoqianmishu;
                            dbContext.dbcontext.Updateable(noticeneeddetail).ExecuteCommand();

                        }
                    }
                }
                dbContext.dbcontext.Insertable(roll).ExecuteCommand();
                RollHelper.CreateStock(roll);
                dbContext.dbcontext.CommitTran();
                txtyijianmishu.Text = Stock.biaoqianmishu.ToString("N2");
                return roll;
                //CalFinishNums();
            }
            catch (Exception ex)
            {
                dbContext.dbcontext.RollbackTran();
                ShowMessage.ShowErrorMessagebox(this, "保存的时候发生了错误：" + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 刷新检验通知单的完成数量
        /// </summary>
        private void ReflashFinishNum()
        {
            if (Detail != null)
            {
                table4.DataSource = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().Where(x => x.ID == Detail.ID).ToList();
            }
        }
        private void Clear(JuanHaoTable roll)
        {
            if (checkbox1.Checked)
            {
                if (Detail != null)
                {
                    LoadInspectionNotice(Detail);
                    LoadLot(Stock);
                    roll = CreateNewRoll();
                }
            }
            if (param.AutoRollNumber)
            {
                txtjuanhao.Text = RollHelper.CreatGangJuanhao(roll).ToString();
            }
            else
            {
                txtjuanhao.Text = (txtjuanhao.Text.ObjToInt() + 1).ToString();
            }
            txtzengsong.Text = "0";
            LoadRolls();
            Defects.Clear();
            File.WriteAllText(Application.StartupPath + "//TempDefects.json", JsonConvert.SerializeObject(Defects));
            table3.DataSource = Defects;
            checkbox1.Checked = false;
            OldRollID = 0;
            txtDengji.Text = string.Empty;
            QueryAll(QueryRoll);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!CheckSave())
            {
                return;
            }
            var roll = Save();
            if (roll != null)
            {
                PrintLabel(PrintStyle.Print, roll, cmbLabels.Text);
            }
            if (radio配货.Checked)
            {
                var details = table4.DataSource as List<InspectionNoticeNeedDetail>;
                if (details != null)
                {
                    var detail = details.FirstOrDefault();
                    if (!string.IsNullOrEmpty(cmbOutShippingmark.Text))
                    {
                        var notic = dbContext.dbcontext.Queryable<InspectionNotice>().First(x => x.DocNum == detail.InspectionNoticeNum);
                        if (notic != null)
                        {
                            if (notic.OutShippingmarkNum > 0)
                            {
                                PrintLabel(PrintStyle.Print, roll, cmbOutShippingmark.Text);
                            }
                        }
                    }
                }
            }
            Clear(roll);
        }
        /// <summary>
        /// 计算已经检验好的米数
        /// </summary>
        //private void CalFinishNums()
        //{
        //    var rolls = dbContext.dbcontext.Queryable<JuanHaoTable >().Where(x => x.OrderNum == txtOrdernum.Text && x.SampleNum  == txtBianhao.Text && x.kuanhao == txtKuanhao.Text
        //    && x.yanse == txtyanse.Text&&x.Ckmc=="仓库"&&x.state==0&&x.DengJI=="A").ToList ();
        //    if(rolls!=null)
        //    {
        //        txtCheckNums.Text =rolls.Sum(x=>x.biaoqianmishu ).ToString ();
        //    }
        //}
        private void PrintLabel(PrintStyle printStyle, JuanHaoTable roll, string shippinpmark)
        {
            try
            {
                var fs = new FastReport.Report();
                fs.Load(Application.StartupPath + "\\Labels\\" + shippinpmark);
                fs.RegisterData(GetData(roll));
                switch (printStyle)
                {
                    case PrintStyle.Preview:
                        fs.Show();
                        break;
                    case PrintStyle.Design:
                        fs.Design();
                        break;
                    case PrintStyle.Print:
                        fs.PrintSettings.Printer = new PrinterSettings().PrinterName;
                        fs.PrintSettings.Copies = cmbCopies.Text.ObjToInt();
                        fs.PrintSettings.ShowDialog = false;
                        fs.Print();
                        break;
                }
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "打印票签的时候发生了错误！" + ex.Message);
            }
        }
        private DataSet GetData(JuanHaoTable roll)
        {
            var dt = ShippingMark.CreateShippingDatatable(roll, 1, 1, string.Empty);
            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            return dataSet;
        }
        private void CreateTable(AntdUI.Table table)
        {
            table.AutoSizeColumnsMode = ColumnsMode.Fill;
            table.Columns = new ColumnCollection();
            table.Columns.AddRange(new AntdUI.Column[] {

                new AntdUI.Column("SampleName","品名",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("GangHao","缸号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("yanse","颜色"),
                new AntdUI.Column("kuanhao","款号"),
                new AntdUI.Column("PiHao","匹号"),
                new AntdUI.Column("biaoqianmishu","票签长度"),
                new AntdUI.Column("Danwei","单位"),
                new AntdUI.Column("rq","打卷日期"),
                 new AntdUI.Column("Ckmc","仓库名称"),
                new AntdUI.Column("OrderNum","订单号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("MaShu","挂码"),
                  new AntdUI.Column("DengJI","等级"),
                 new AntdUI.Column("JiaJian","赠送"),
                new AntdUI.Column("JuanHao","条码"),
            });
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if (!string.IsNullOrEmpty(txtganghao.Text))
            //{
            //    if (Stock != null)
            //    {

            //        if (ShowMessage.ShowIsCheckDoneBox(this, "当前缸号     "+txtganghao.Text+ "    是否已经全部检验完毕?\r\n没有布料未检验了") == DialogResult.OK)
            //        {
            //            RollHelper.CalculateInventoryQuantity(Stock);
            //            dbContext.dbcontext.Updateable(Stock).ExecuteCommand();
            //        }
            //    }
            //}
            param.Shippingmark = cmbLabels.Text;
            param.Copies = cmbCopies.Text.ObjToInt();
            param.MachineID = txtjitaihao.Text.ObjToInt();
            File.WriteAllText(Application.StartupPath + "//Setting.json", JsonConvert.SerializeObject(param));
            Defects.Clear();
            Detail = null;
            Stock= null;
            FileHelper.保存信息(new Temp() { Defects = Defects, Detail = Detail, Stock = Stock });
            comService?.关闭端口();
        }

        private Boolean CheckSave()
        {
            if (!BeginSave())
            {
                return false;
            }
            if (!CheckNeed())
            {
                return false;
            }
            if (!CheckDengji())
            {
                return false;
            }
            if (!CheckDengji())
            {
                return false;
            }
            return true;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (!CheckSave())
            {
                return;
            }
            Clear(Save());
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                var rolls = table1.DataSource as List<JuanHaoTable>;
                if (rolls != null)
                {
                    if (rolls.Count > 0)
                    {
                        if (table1.SelectedIndex > 0)
                        {
                            var roll = rolls[table1.SelectedIndex - 1];
                            if (!string.IsNullOrEmpty(roll.InspectionNoticeNum))
                            {
                                var noticedoc = dbContext.dbcontext.Queryable<InspectionNotice>().First(x => x.DocNum == roll.InspectionNoticeNum);
                                if (noticedoc != null)
                                {
                                    PrintLabel(PrintStyle.Print, roll, noticedoc.ShinppingMark);
                                    if (!string.IsNullOrEmpty(noticedoc.OutShinppingMark))
                                    {
                                        PrintLabel(PrintStyle.Print, roll, noticedoc.OutShinppingMark);
                                    }
                                }
                            }
                            else
                            {
                                var order = dbContext.dbcontext.Queryable<OrderTable>().First(x => x.OrderNum == roll.OrderNum);
                                if (order != null)
                                {
                                    PrintLabel(PrintStyle.Print, roll, order.ShippingMark);
                                }
                                else
                                {
                                    PrintLabel(PrintStyle.Print, roll, cmbLabels.Text);
                                }
                            }
                        }
                        else
                        {
                            ShowMessage.ShowErrorMessagebox(this, "请点击一下你要重打的卷");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "重打票签的时候发生了错误：" + ex.Message);
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要删除当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table1.DataSource as List<JuanHaoTable>;
                if (table1.SelectedIndex > 0)
                {
                    try
                    {
                        var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table1.SelectedIndex - 1].JuanHao);
                        if (roll != null)
                        {
                            if (roll.state == 0)
                            {
                                using (var trans = dbContext.dbcontext.UseTran())
                                {
                                    dbContext.dbcontext.Deleteable(roll).ExecuteCommand();
                                    dbContext.dbcontext.Deleteable<ChiDianTable>().Where(x => x.JuanHao == roll.JuanHao).ExecuteCommand();
                                   //删除时的库存处理
                                    var stock = RollHelper.QueryStockWithRoll(roll);
                                    if (stock != null)
                                    {
                                        RollHelper.ReduceYijianmishu(stock, roll);
                                        if (stock.MS == 0 && stock.JS == 0)
                                        {
                                            dbContext.dbcontext.Deleteable(stock).ExecuteCommand();
                                        }
                                        else
                                        {
                                            dbContext.dbcontext.Updateable(stock).ExecuteCommand();
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(roll.InspectionNoticeNum))
                                    {
                                        if (roll.DengJI == "A")
                                        {
                                            var needdetail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.InspectionNoticeNum == roll.InspectionNoticeNum && x.sampleNum == roll.SampleNum
                                            && x.Kuanhao == roll.kuanhao && x.color == roll.yanse && x.OrderNum == roll.OrderNum && x.ContractNum == roll.Hetonghao);
                                            if (needdetail != null)
                                            {
                                                needdetail.FinishNum -= roll.biaoqianmishu;
                                                dbContext.dbcontext.Updateable(needdetail).ExecuteCommand();
                                            }
                                            if (Detail != null && needdetail != null)
                                            {
                                                if (needdetail.ID == Detail.ID)
                                                {
                                                    table4.DataSource = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().Where(x => x.ID == Detail.ID).ToList();
                                                }
                                            }
                                        }
                                    }
                                    trans.CommitTran();
                                }
                            }
                            else
                            {
                                ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能删除");
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        ShowMessage.ShowErrorMessagebox(this, "删除的时候发生了错误：" + ex.Message);
                    }
                }
                else
                {
                    ShowMessage.ShowErrorMessagebox(this, "请点击一下你要删除的卷");
                }
            }
            LoadRolls();
            txtjuanhao.Text = RollHelper.CreatGangJuanhao(CreateNewRoll()).ToString();
            //CalFinishNums();
        }
        /// <summary>
        /// 库存编号了 重新赋值
        /// </summary>
        /// <param name="stock"></param>
        private void StockChange(StockTable stock)
        {
            txtganghao.Text = stock.GH;
            txtyanse.Text = stock.YS;
            txtStockname.Text = stock.CKMC;
            txtBianhao.Text = stock.BH;
            txtpingming.Text = stock.PM;
            txtguama.Text = "100";
            cmbDanwei.Text = "米";
            txtrukumishu.Text = stock.RukuNum.ToString();
            txtyijianmishu.Text = stock.yijianmishu.ToString();
            //txtorderNums.Text = fm.selectdb.NeedNum.ToString();
            txtkezhong.Text = stock.KZ;
            txtyijianmishu.Text = stock.biaoqianmishu.ToString("N0");
        }
        private void LoadLot(StockTable stock)
        {
            txtganghao.Text = stock.GH;
            Stock = stock;
            MiddleCheck();
            if (stock != null)
            {
                txtStockname.Text = stock.CKMC;
                if (param.AutoRollNumber)
                {
                    var roll = CreateNewRoll();
                    txtjuanhao.Text = RollHelper.CreatGangJuanhao(roll).ToString();
                }
            }
        }
        private void button9_Click(object sender, EventArgs e)
        {
            var detail = table4.DataSource as List<InspectionNoticeNeedDetail>;
            if (radio配货.Checked&&detail==null)
            {
                ShowMessage.ShowErrorMessagebox(this, "请先加载检验通知单");
                return;
            }
            if (!string.IsNullOrEmpty(txtganghao.Text))
            {
                if (Stock != null)
                {
                    if (ShowMessage.ShowIsCheckDoneBox(this, "当前缸号  "+txtganghao.Text +"   " +
                        "是否已经全部检验完毕?\r\n没有布料未检验了") == DialogResult.OK)
                    {
                        RollHelper.CalculateInventoryQuantity(Stock);
                        dbContext.dbcontext.Updateable(Stock).ExecuteCommand();
                    }
                }
            }
            try
            {
                var fm = new SelectLotFrm(param,radio配货.Checked);
                fm.ShowDialog();
                if (fm.selectdb != null)
                {
                    LoadLot(fm.selectdb);
                }
               
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "生成卷号的时候发生了错误：" + ex.Message);
            }
            FileHelper.保存信息(new Temp() { Defects = Defects, Detail = Detail, Stock = Stock });
        }
        private void InsertRukutable(StockTable s)
        {
            var ruku = new RukuTable()
            {
                LX = "检验完毕",
               
            };
            ruku.MapperFrom(s);
            ruku.CustomerLotNo = s.ID.ToString();
            dbContext.dbcontext.Insertable(ruku).ExecuteCommand();
        }
        //rukutable.

        private void txtLength_Click(object sender, EventArgs e)
        {
            txtLength.SelectAll();
            if (!switch1.Checked)
            {
                KeyboardHelper.ShowKeyboard("number", "请输入长度" + txtLength.Text);
            }
        }
        /// <summary>
        /// 创建疵点名称按钮
        /// </summary>
        private void CreateCidianBtn()
        {
            var cidians = dbContext.dbcontext.Queryable<CiDianNameTable>().ToList();
            foreach (var item in cidians)
            {
                var btn = new UIButton() { Width = 80, Height = 40, Font = new Font("Microsoft YaHei", 10) };
                btn.Text = item.CiDianName + $"({item.Daihao})";
                btn.Click += Btn_Click;
                uiFlowLayoutPanel1.Controls.Add(btn);
            }

        }
        private void Btn_Click(object sender, EventArgs e)
        {
            var btn = sender as UIButton;
            var defect = new ChiDianTable() { ChiDianName = btn.Text.Split('(')[0], WeiZhi = txtLength.Text };
            var fm = new InputDefect() { Defect = defect };
            fm.ShowDialog();
            if (fm.Defect != null)
            {
                Defects.Add(defect);
                table3.DataSource = Defects;
               FileHelper.保存信息(new Temp() { Defects = Defects, Detail = Detail, Stock = Stock });
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            var defect = table3.DataSource as List<ChiDianTable>;
            if (table3.SelectedIndex > 0)
            {
                defect.RemoveAt(table3.SelectedIndex - 1);
                table3.DataSource = defect;
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            var defect = table3.DataSource as List<ChiDianTable>;
            defect.Clear();
            table3.DataSource = defect;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            var defects = table3.DataSource as List<ChiDianTable>;
            if (defects.Count > 0)
            {
                var fm = new InputDefect() { Defect = defects[table3.SelectedIndex - 1] };
                fm.ShowDialog();
                table3.DataSource = defects;
            }
        }
        private void QueryAll(JuanHaoTable roll)
        {
            var rolls = dbContext.dbcontext.Queryable<JuanHaoTable>().Where(x => x.GangHao.Contains(roll.GangHao) && x.OrderNum.Contains(roll.OrderNum)
            && x.yanse.Contains(roll.yanse) && x.Hetonghao.Contains(roll.Hetonghao) && x.state == 0).OrderByDescending(x => x.rq).ToList();
            table2.DataSource = rolls;
            label28.Text = "合计:" + rolls.Count + "卷" + "     长度：" + rolls.Sum(x => x.biaoqianmishu).ToString();
        }
        private void button5_Click(object sender, EventArgs e)
        {
            var fm = new QueryParamsView();
            fm.ShowDialog();
            if (fm.Roll != null)
            {
                QueryRoll = fm.Roll;
                QueryAll(QueryRoll);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要删除当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table2.DataSource as List<JuanHaoTable>;
                if (table2.SelectedIndex > 0)
                {
                    dbContext.dbcontext.Deleteable(rolls[table2.SelectedIndex - 1]).ExecuteCommand();
                    var roll = rolls[table2.SelectedIndex - 1];
                    dbContext.dbcontext.Deleteable<ChiDianTable>().Where(x => x.JuanHao == roll.JuanHao).ExecuteCommand();
                    if (!string.IsNullOrEmpty(roll.InspectionNoticeNum))
                    {
                        if (roll.DengJI == "A")
                        {
                            var needdetail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.InspectionNoticeNum == roll.InspectionNoticeNum && x.sampleNum == roll.SampleNum
                            && x.Kuanhao == roll.kuanhao && x.color == roll.yanse && x.OrderNum == roll.OrderNum && x.ContractNum == roll.Hetonghao);
                            if (needdetail != null)
                            {
                                needdetail.FinishNum -= roll.biaoqianmishu;
                                dbContext.dbcontext.Updateable(needdetail).ExecuteCommand();
                            }
                            if (Detail != null && needdetail != null)
                            {
                                if (needdetail.ID == Detail.ID)
                                {
                                    table4.DataSource = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().Where(x => x.ID == Detail.ID).ToList();
                                }
                            }
                        }
                    }
                    //库存处理
                    var stock = RollHelper.QueryStockWithRoll(roll);
                    if (stock != null)
                    {
                        RollHelper.CalculateInventoryQuantity(stock);
                        dbContext.dbcontext.Updateable(stock).ExecuteCommand();
                    }
                }
                QueryAll(QueryRoll);
            }
            //CalFinishNums();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            var rolls = table2.DataSource as List<JuanHaoTable>;
            if (table2.SelectedIndex > 0)
            {
                PrintLabel(PrintStyle.Print, rolls[table2.SelectedIndex - 1], cmbLabels.Text);
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtDengji_Click(object sender, EventArgs e)
        {
            var fm = new SelectClassias();
            fm.ShowDialog();
            txtDengji.Text = fm.Grade;
        }

        private void txtStockname_Click(object sender, EventArgs e)
        {
            if (param.OutsideInspection != "是")
            {
                var fm = new SelectStockname();
                fm.ShowDialog();
                txtStockname.Text = fm.StockName;
            }
        }

        private void input5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                QueryAll(QueryRoll);
            }
        }
        private void LoadInspectionNotice(InspectionNoticeNeedDetail detail)
        {
            table4.DataSource = new List<InspectionNoticeNeedDetail>() { detail };
            Detail = detail;
            var doc = dbContext.dbcontext.Queryable<InspectionNotice>().First(x => x.DocNum == detail.InspectionNoticeNum);
            if (doc != null)
            {
                txtOrdernum.Text = detail.OrderNum;
                txtKuanhao.Text = detail.Kuanhao;
                txtguama.Text = "100";
                cmbDanwei.Text = detail.Unit == "码" ? detail.Unit:(detail.Unit == "Y" ? "码" : "米");
                comService.SetUnit(cmbDanwei.Text);
                txtCustomColor.Text = detail.color;
                txtHetonghao.Text = detail.ContractNum;
                txtCustomColor.Text = detail.color;
                txtCustomFricename.Text = detail.CustomerPingMing;
                txtpingming.Text = detail.sampleName;
                txtBianhao.Text = detail.sampleNum;
                txtyanse.Text = detail.color;
                //txtorderNums.Text = fm.selectdb.NeedNum.ToString();
                cmbCopies.Text = doc.InShippingmarkNum.ToString();
                txtkezhong.Text = detail.weight;
                groupBox1.Text = doc.StockName;
                if (!string.IsNullOrEmpty(doc.ShinppingMark))
                {
                    cmbLabels.Text = doc.ShinppingMark;
                }
                if (!string.IsNullOrEmpty(doc.OutShinppingMark))
                {
                    cmbOutShippingmark.Text = doc.OutShinppingMark;
                }
                if (doc.CompletionOrintermediate == "成检")
                {
                    radio配货.Checked = true;
                }
                else
                {
                    if (doc.CompletionOrintermediate == "中检")
                    {
                        radio中检.Checked = true;
                    }
                    else
                    {
                        radio库存.Checked = true;
                    }
                }
            }
            table4.DataSource = table4.DataSource;
        }
        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
                var noticenum=string .Empty;
                if (table4.DataSource!=null)
                {
                    var details = table4.DataSource as List<InspectionNoticeNeedDetail>;
                    if (details != null)
                    {
                        if (details.Count > 0)
                        {
                           noticenum= details[0].InspectionNoticeNum;
                        }
                    }
                }
                var fm = new FabricSelectFrm(noticenum);
                fm.ShowDialog();
                if (fm.selectdb != null)
                {
                    Detail = fm.selectdb;
                    LoadInspectionNotice(Detail);
                }
                FileHelper.保存信息(new Temp() { Defects = Defects, Detail = Detail, Stock = Stock });
                //CalFinishNums();
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "选择布料的时候发生了错误" + ex.Message);
            }
        }

        private void switch1_CheckedChanged(object sender, BoolEventArgs e)
        {
            if (switch1.Checked)
            {
                comService.打开端口(param.ComNum);
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }
        }

        private void chkchengjian_CheckedChanged(object sender, BoolEventArgs e)
        {
            Detail = null;
            table4.DataSource = null;
        }
        private void MiddleCheck()
        {
            if (Stock != null)
            {
                StockChange(Stock);
                if (!radio配货.Checked)
                {
                    groupBox1.Text = string.Empty;
                    var item = dbContext.dbcontext.Queryable<Setting>().First(x => x.settingname == "中性唛头");
                    if (item != null)
                    {
                        cmbLabels.Text = item.settingValue;
                    }
                    cmbOutShippingmark.Text = string.Empty;
                }
              
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            var fm = new SelectEmployer();
            fm.ShowDialog();
            txtjianyanyuan.Text = fm.Employer;
        }
        private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            System.Windows.Forms.TextBox textBox = sender as System.Windows.Forms.TextBox;

            // 允许数字、控制键和一个小数点
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
                return;
            }

            // 处理小数点输入
            if (e.KeyChar == '.')
            {
                // 禁止多个小数点
                if (textBox.Text.Contains('.'))
                {
                    e.Handled = true;
                    return;
                }

                // 禁止小数点作为第一个字符
                if (textBox.SelectionStart == 0)
                {
                    e.Handled = true;
                    return;
                }

                // 禁止在负号后直接输入小数点
                if (textBox.Text.StartsWith("-") && textBox.SelectionStart == 1)
                {
                    e.Handled = true;
                }
            }
        }
        private string lastValidText = "";
        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            System.Windows.Forms.TextBox textBox = sender as System.Windows.Forms.TextBox;

            // 使用正则表达式验证完整输入
            if (Regex.IsMatch(textBox.Text, @"^-?\d*\.?\d*$"))
            {
                lastValidText = textBox.Text;
            }
            else
            {
                // 恢复上次有效文本
                int selectionStart = textBox.SelectionStart;
                textBox.Text = lastValidText;
                textBox.SelectionStart = selectionStart - 1;
            }

            // 处理空文本框的情况
            if (string.IsNullOrEmpty(textBox.Text))
            {
                lastValidText = "";
            }
        }

        private void txtLength_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (param.AutoWeight)
                {
                    decimal menfu = Convert.ToDecimal(txtmenfu.Text);
                    decimal kezhong = txtkezhong.Text.ToDecimal();
                    decimal weight = menfu * kezhong * txtLength.Text.ToDecimal() / 1000 / 10;
                    txtWeight.Text = weight.ToString("N2");
                }
            }
            catch
            {
                txtWeight.Text = "0.00";
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            var fm = new SelectStockname();
            fm.ShowDialog();
            var stockname = txtStockname.Text;
            txtStockname.Text = fm.StockName;
            if (!BeginSave())
            {
                txtStockname.Text = stockname;
                return;
            }
            Save();
            txtStockname.Text = stockname;
            LoadRolls();
        }

        private void cmbDanwei_TextChanged(object sender, EventArgs e)
        {
            comService.SetUnit(cmbDanwei.Text);
        }

        private void txtganghao_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void txtmenfu_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void txtguama_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void txtjuanhao_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void txtjitaihao_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void button12_Click_1(object sender, EventArgs e)
        {
            var rolls = table1.DataSource as List<JuanHaoTable>;
            if (table1.SelectedIndex > 0)
            {
                try
                {
                    var roll = rolls[table1.SelectedIndex - 1];
                    if (roll != null)
                    {
                        new ShowDefect(roll).ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "查看疵点的时候发生了错误：" + ex.Message);
                }
            }
            else
            {
                ShowMessage.ShowErrorMessagebox(this, "请点击一下你要复检的卷");
            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要复检当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table1.DataSource as List<JuanHaoTable>;
                if (table1.SelectedIndex > 0)
                {
                    try
                    {
                        var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table1.SelectedIndex - 1].JuanHao);
                        if (roll != null)
                        {
                            if (roll.state == 1)
                            {
                                ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能复检");
                                return;
                            }
                            table3.DataSource = dbContext.dbcontext.Queryable<ChiDianTable>().Where(x => x.JuanHao == roll.JuanHao).ToList();
                            txtBianhao.Text = roll.SampleNum;
                            txtCustomColor.Text = roll.CustomerColorNum;
                            txtCustomFricename.Text = roll.CustomerPingMing;
                            txtDengji.Text = roll.DengJI;
                            txtganghao.Text = roll.GangHao;
                            txtguama.Text = roll.MaShu.ToString();
                            txtHetonghao.Text = roll.Hetonghao;
                            txtjitaihao.Text = roll.MachineID;
                            txtjuanhao.Text = roll.PiHao.ToString();
                            txtkezhong.Text = roll.Kezhong;
                            txtKuanhao.Text = roll.kuanhao;
                            txtmenfu.Text = roll.Menfu;
                            txtOrdernum.Text = roll.OrderNum;
                            txtpingming.Text = roll.SampleName;
                            txtStockname.Text = roll.Ckmc;
                            txtWeight.Text = roll.Weight.ToString("N2");
                            txtyanse.Text = roll.yanse;
                            txtzengsong.Text = roll.JiaJian.ToString("N0");
                            cmbDanwei.Text = roll.Danwei;
                            checkbox1.Checked = true;
                            OldRollID = roll.ID;
                            txtbeizhu.Text = roll.Cidian;
                            Stock = RollHelper.QueryStockWithRoll(roll);
                        }
                        else
                        {
                            ShowMessage.ShowErrorMessagebox(this, "该卷已经不存在！不能复检");
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage.ShowErrorMessagebox(this, "复检的时候发生了错误：" + ex.Message);
                    }
                }
            }

        }

        private void button17_Click(object sender, EventArgs e)
        {
            var rolls = table1.DataSource as List<JuanHaoTable>;
            if (table1.SelectedIndex > 0)
            {
                try
                {
                    var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table1.SelectedIndex - 1].JuanHao);
                    if (roll != null)
                    {
                        if (roll.state == 1)
                        {
                            ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能开卷");
                            return;
                        }
                        new Uncoiling(roll).ShowDialog();
                        LoadRolls();
                    }
                    else
                    {
                        ShowMessage.ShowErrorMessagebox(this, "该卷已经不存在！不能开卷");
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "查看疵点的时候发生了错误：" + ex.Message);
                }
            }
            else
            {
                ShowMessage.ShowErrorMessagebox(this, "请点击一下你要开剪的卷");
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            var rolls = table1.DataSource as List<JuanHaoTable>;
            if (table1.SelectedIndex > 0)
            {
                try
                {
                    var roll = rolls[table1.SelectedIndex - 1];
                    var checkrolls = dbContext.dbcontext.Queryable<JuanHaoTable>().Where(x => x.GangHao == roll.GangHao && x.OrderNum == roll.OrderNum &&
                    x.kuanhao == roll.kuanhao && x.Hetonghao == roll.Hetonghao && x.yanse == roll.yanse && x.Houzhengli == roll.Houzhengli && x.SampleNum == roll.SampleNum).OrderBy(x => x.PiHao).ToList();
                    打印检验报告.PrintReport(PrintUseful.Privew, checkrolls, "CheckDoc.frx", string.Empty);
                }

                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "打印检验报告的时候发生了错误：" + ex.Message);
                }
            }
            else
            {
                ShowMessage.ShowErrorMessagebox(this, "请点击一下你要查看的卷");
            }
        }

        private void input7_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("number", "输入");
        }

        private void button21_Click(object sender, EventArgs e)
        {
            var rolls = table2.DataSource as List<JuanHaoTable>;
            if (table2.SelectedIndex > 0)
            {
                try
                {
                    var roll = rolls[table2.SelectedIndex - 1];
                    if (roll != null)
                    {
                        new ShowDefect(roll).ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "查看疵点的时候发生了错误：" + ex.Message);
                }
            }

        }
        private void button20_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要复检当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table2.DataSource as List<JuanHaoTable>;
                if (table2.SelectedIndex > 0)
                {
                    try
                    {
                        var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table2.SelectedIndex - 1].JuanHao);
                        if (roll != null)
                        {
                            if (roll.state == 1)
                            {
                                ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能复检");
                                return;
                            }
                            table3.DataSource = dbContext.dbcontext.Queryable<ChiDianTable>().Where(x => x.JuanHao == roll.JuanHao).ToList();
                            txtBianhao.Text = roll.SampleNum;
                            txtCustomColor.Text = roll.CustomerColorNum;
                            txtCustomFricename.Text = roll.CustomerPingMing;
                            txtDengji.Text = roll.DengJI;
                            txtganghao.Text = roll.GangHao;
                            txtguama.Text = roll.MaShu.ToString();
                            txtHetonghao.Text = roll.Hetonghao;
                            txtjitaihao.Text = roll.MachineID;
                            txtjuanhao.Text = roll.PiHao.ToString();
                            txtkezhong.Text = roll.Kezhong;
                            txtKuanhao.Text = roll.kuanhao;
                            txtmenfu.Text = roll.Menfu;
                            txtOrdernum.Text = roll.OrderNum;
                            txtpingming.Text = roll.SampleName;
                            txtStockname.Text = roll.Ckmc;
                            txtWeight.Text = roll.Weight.ToString("N2");
                            txtyanse.Text = roll.yanse;
                            txtzengsong.Text = roll.JiaJian.ToString("N0");
                            cmbDanwei.Text = roll.Danwei;
                            checkbox1.Checked = true;
                            OldRollID = roll.ID;
                            txtbeizhu.Text = roll.Cidian;
                            Stock = RollHelper.QueryStockWithRoll(roll);
                        }
                        else
                        {
                            ShowMessage.ShowErrorMessagebox(this, "该卷已经不存在！不能复检");
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage.ShowErrorMessagebox(this, "查看疵点的时候发生了错误：" + ex.Message);
                    }
                }
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            var rolls = table2.DataSource as List<JuanHaoTable>;
            if (table2.SelectedIndex > 0)
            {
                try
                {
                    var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table2.SelectedIndex - 1].JuanHao);
                    if (roll != null)
                    {
                        if (roll.state == 1)
                        {
                            ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能开卷");
                            return;
                        }
                        new Uncoiling(roll).ShowDialog();
                        QueryAll(QueryRoll);
                    }
                    else
                    {
                        ShowMessage.ShowErrorMessagebox(this, "该卷已经不存在！不能开卷");
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "查看疵点的时候发生了错误：" + ex.Message);
                }
            }
        }

        private void button22_Click(object sender, EventArgs e)
        {
            var rolls = table2.DataSource as List<JuanHaoTable>;
            if (table2.SelectedIndex > 0)
            {
                try
                {
                    var roll = rolls[table2.SelectedIndex - 1];
                    var checkrolls = dbContext.dbcontext.Queryable<JuanHaoTable>().Where(x => x.GangHao == roll.GangHao && x.OrderNum == roll.OrderNum &&
                    x.kuanhao == roll.kuanhao && x.Hetonghao == roll.Hetonghao && x.yanse == roll.yanse && x.Houzhengli == roll.Houzhengli && x.SampleNum == roll.SampleNum).OrderBy(x => x.PiHao).ToList();
                    打印检验报告.PrintReport(PrintUseful.Privew, checkrolls, "CheckDoc.frx", string.Empty);
                }

                catch (Exception ex)
                {
                    ShowMessage.ShowErrorMessagebox(this, "打印检验报告的时候发生了错误：" + ex.Message);
                }
            }
        }

        private void txtzengsong_Click(object sender, EventArgs e)
        {
            KeyboardHelper.ShowKeyboard("Number", "输入");
        }

        private void button23_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要将当前选中的细码转为库存吗？") == DialogResult.OK)
            {
                var rolls = table1.DataSource as List<JuanHaoTable>;
                if (table1.SelectedIndex > 0)
                {
                    try
                    {
                        var roll = dbContext.dbcontext.Queryable<JuanHaoTable>().First(x => x.JuanHao == rolls[table1.SelectedIndex - 1].JuanHao);
                        if (roll != null)
                        {
                            if (roll.state == 0)
                            {
                                using (var trans = dbContext.dbcontext.UseTran())
                                {
                                    if (!string.IsNullOrEmpty(roll.InspectionNoticeNum))
                                    {
                                        if (roll.DengJI == "A")
                                        {
                                            var needdetail = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().First(x => x.InspectionNoticeNum == roll.InspectionNoticeNum && x.sampleNum == roll.SampleNum
                                            && x.Kuanhao == roll.kuanhao && x.color == roll.yanse && x.OrderNum == roll.OrderNum && x.ContractNum == roll.Hetonghao);
                                            if (needdetail != null)
                                            {
                                                needdetail.FinishNum -= roll.biaoqianmishu;
                                                dbContext.dbcontext.Updateable(needdetail).ExecuteCommand();
                                            }
                                            if (Detail != null && needdetail != null)
                                            {
                                                if (needdetail.ID == Detail.ID)
                                                {
                                                    table4.DataSource = dbContext.dbcontext.Queryable<InspectionNoticeNeedDetail>().Where(x => x.ID == Detail.ID).ToList();
                                                }
                                            }
                                        }
                                    }
                                    roll.InspectionNoticeNum = string.Empty;
                                    roll.CheckStyle = "库存";
                                    roll.Consignee = string.Empty;
                                    roll.CustomerPingMing = string.Empty;
                                    roll.CustomerColorNum = string.Empty;
                                    roll.CustomerName = string.Empty;
                                    dbContext.dbcontext.Updateable(roll).ExecuteCommand();
                                    trans.CommitTran();
                                }
                            }
                            else
                            {
                                ShowMessage.ShowErrorMessagebox(this, "该卷已经出库不能删除");
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        ShowMessage.ShowErrorMessagebox(this, "删除的时候发生了错误：" + ex.Message);
                    }
                }
                else
                {
                    ShowMessage.ShowErrorMessagebox(this, "请点击一下你要转为库存的卷");
                }
            }
            LoadRolls();
            txtjuanhao.Text = RollHelper.CreatGangJuanhao(CreateNewRoll()).ToString();
        }

        private void chkzidongjuanhao_CheckedChanged(object sender, BoolEventArgs e)
        {
          param.AutoRollNumber = chkzidongjuanhao.Checked;
        }

        private void button24_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            var fm = new SettingFrm(param);
            fm.ShowDialog();
            comService.Stopwatch = param.Stopwatch;
            comService.BaudRate = param.BaudRate.ObjToInt();
            if (switch1.Checked)
            {
                comService.打开端口(param.ComNum);
                timer1.Start();
            }
        }

        private void radio配货_Click(object sender, EventArgs e)
        {
                ///当切换成成检的时候情况库存信息  必须重新选择
                StockChange(new StockTable());
        }

        private void radio中检_Click(object sender, EventArgs e)
        {
            Detail = null;
            table4.DataSource = null;
            MiddleCheck();
        }

        private void radio库存_Click(object sender, EventArgs e)
        {
            Detail = null;
            table4.DataSource = null;
            MiddleCheck();
        }
    }
}
